package com.jlcloud.core.oauth2.granter;

import com.jlcloud.core.launch.constant.TokenConstant;
import com.jlcloud.core.oauth2.handler.PasswordHandler;
import com.jlcloud.core.oauth2.provider.OAuth2Request;
import com.jlcloud.core.oauth2.provider.OAuth2Token;
import com.jlcloud.core.oauth2.service.OAuth2Client;
import com.jlcloud.core.oauth2.service.OAuth2ClientService;
import com.jlcloud.core.oauth2.service.OAuth2User;
import com.jlcloud.core.oauth2.service.OAuth2UserService;
import com.jlcloud.core.oauth2.service.impl.OAuth2ClientDetail;
import com.jlcloud.core.oauth2.service.impl.OAuth2UserDetail;
import com.jlcloud.core.oauth2.utils.OAuth2Util;
import com.jlcloud.core.secure.TokenInfo;
import com.jlcloud.core.tool.utils.Func;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * ImplicitGranter
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@Component
public class ImplicitGranter extends AbstractTokenGranter {

	public ImplicitGranter(OAuth2ClientService clientService, OAuth2UserService userService, PasswordHandler passwordHandler) {
		super(clientService, userService, passwordHandler);
	}

	@Override
	public String type() {
		return IMPLICIT;
	}

	@Override
	public OAuth2Client client(OAuth2Request request) {
		return new OAuth2ClientDetail();
	}

	@Override
	public OAuth2User user(OAuth2Request request) {
		OAuth2UserDetail user = new OAuth2UserDetail();
		user.setAccount(request.getUsername());
		user.setName(request.getUsername());
		return Optional.ofNullable(this.enhancer)
			.map(enhancer -> enhancer.enhance(user, request))
			.orElse(user);
	}

	@Override
	public OAuth2Token token(OAuth2User user, OAuth2Request request) {
		TokenInfo accessToken = OAuth2Util.createImplicitAccessToken(user);

		OAuth2Token token = OAuth2Token.create();

		token.getArgs().set(TokenConstant.USER_NAME, user.getAccount())
			.set(TokenConstant.AVATAR, Func.toStr(user.getAvatar(), TokenConstant.DEFAULT_AVATAR))
			.set(TokenConstant.ACCESS_TOKEN, accessToken.getToken())
			.set(TokenConstant.TOKEN_TYPE, TokenConstant.BEARER)
			.set(TokenConstant.EXPIRES_IN, accessToken.getExpire())
			.set(TokenConstant.DETAIL, user.getDetail())
			.set(TokenConstant.LICENSE, TokenConstant.LICENSE_NAME);

		return token.setAccessToken(accessToken.getToken()).setAccessTokenExpire(accessToken.getExpire());
	}

}
